package socket

import (
	"encoding/json"
	"github.com/gorilla/websocket"
	"time"
)

const (
	// Time allowed to read the next pong message from the peer.
	pongWait = 60 * time.Second
	// Maximum message size allowed from peer.
	maxMessageSize = 512
)

type Client struct {
	ID     string
	Socket *websocket.Conn
	Send   chan []byte
}

// Write 通过websocket协议向连接到ws的客户端发送数据.
func (c *Client) Write() {
	defer func() {
		c.Socket.Close()
	}()
	for {
		select {
		case message, ok := <-c.Send:
			if !ok {
				c.Socket.WriteMessage(websocket.CloseMessage, []byte{})
				return
			}
			c.Socket.WriteMessage(websocket.TextMessage, message)
		}
	}
}

// Read 读取在websocket管道中的数据.
func (c *Client) Read() {
	defer func() {
		Hub.Unregister <- c
		c.Socket.Close()
	}()
	c.Socket.SetReadLimit(maxMessageSize)
	c.Socket.SetReadDeadline(time.Now().Add(pongWait))
	c.Socket.SetPongHandler(func(string) error { c.Socket.SetReadDeadline(time.Now().Add(pongWait)); return nil })
	for {
		_, message, err := c.Socket.ReadMessage()
		if err != nil {
			break
		}
		if string(message) == "PING" {
			c.Socket.PingHandler()("")
		}
		jsonMessage, _ := json.Marshal(map[string]interface{}{"Sender": c.ID, "Content": string(message)})
		Hub.Broadcast <- jsonMessage
	}
}
